import json
import logging
from pathlib import Path
from typing import Dict, Any

class ConfigManager:
    """配置管理器"""
    def __init__(self, config_file: str = "config.json"):
        self.config_file = Path(config_file)
        self.logger = logging.getLogger(__name__)
        self._load_config()
    
    def _load_config(self):
        """加载配置"""
        try:
            if self.config_file.exists():
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    self.config = json.load(f)
            else:
                self.config = self._get_default_config()
                self.save_config()
        except Exception as e:
            self.logger.error(f"加载配置失败: {str(e)}")
            self.config = self._get_default_config()
    
    def _get_default_config(self) -> Dict:
        """获取默认配置"""
        return {
            "server": {
                "host": "localhost",
                "port": 11434
            },
            "ui": {
                "theme": "light",
                "language": "zh_CN"
            },
            "chat": {
                "model": "llama2",
                "temperature": 0.7,
                "max_length": 2000
            }
        }
    
    def save_config(self) -> bool:
        """保存配置"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=2, ensure_ascii=False)
            return True
        except Exception as e:
            self.logger.error(f"保存配置失败: {str(e)}")
            return False 